package com.zx.oa.controller;

import com.alibaba.fastjson.JSON;
import com.zx.oa.entity.ClassInfo;
import com.zx.oa.entity.Major;
import com.zx.oa.service.ClassInfo.ClassInfoService;
import com.zx.oa.service.ClassInfo.ClassInfoServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/studentAjax.do")
public class StudentAjax extends HttpServlet {

    ClassInfoService classInfoServlet=new ClassInfoServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String param=request.getParameter("operation");
        if("major".equals(param)){
            majorServlet(request,response);
        } else if ("class".equals(param)) {
            classServlet(request,response);
        }
    }

    private void classServlet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        String major=request.getParameter("major");
        List<ClassInfo> classInfoList= classInfoServlet.getClassInfoByStudyType(major);
        String jsonResult=JSON.toJSONString(classInfoList);
        PrintWriter out=response.getWriter();
        out.print(jsonResult);
        out.flush();
        out.close();
    }

    private void majorServlet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        List<Major> majorList= (List<Major>) request.getSession().getAttribute("majors");
        String jsonResult=JSON.toJSONString(majorList);
        PrintWriter out=response.getWriter();
        out.print(jsonResult);
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
